const db = require("../db/index");

const loginLogController = {
  // 登录记录
  loginLog: async (req, res) => {
    const { account, name, email } = req.body;
    const login_time = new Date();

    const sql = "INSERT INTO login_log SET ?";
    try {
      await db.query(sql, { account, name, email, login_time });
      res.send({
        status: 1,
        message: "成功",
      });
    } catch (err) {
      res.cc("登陆失败，请稍后再试");
    }
  },
  // 获取登录记录列表
  loginLogList: async (req, res) => {
    const { page } = req.query;
    const sql = `SELECT * FROM login_log ORDER BY login_time DESC LIMIT 10 OFFSET ${
      (page - 1) * 10
    }`;
    const sql1 = `SELECT * FROM login_log`;
    try {
      const [data] = await db.query(sql);
      const [total] = await db.query(sql1);
      res.send({
        status: 1,
        message: "成功",
        data: data,
        total: total.length,
      });
    } catch (err) {
      res.cc(err);
    }
  },
  // 搜索最近十条登录记录列表
  searchloginLogList: async (req, res) => {
    const { account } = req.query;
    const sql = `SELECT * FROM login_log WHERE account = ? LIMIT 10 OFFSET 0`;
    try {
      const [data] = await db.query(sql, account);
      res.send({
        status: 1,
        message: "成功",
        data: data,
      });
    } catch (err) {
      res.cc(err);
    }
  },
  // 清空登录日志
  clearLoginLog: async (req, res) => {
    const sql = "TRUNCATE TABLE login_log";
    try {
      await db.query(sql);
      res.send({
        status: 1,
        message: "成功",
      });
    } catch (err) {
      res.cc(err);
    }
  },
};

module.exports = loginLogController;
